//# 应用根视图
define(['jquery', 'underscore', 'backbone', 'echarts', 'toastr'],
    function ($, _, Backbone, Echart, Toastr) {
        var RootView = Backbone.View.extend({

            el: 'body',

            /**
             * 初始化页面展示:
             * 包括组件渲染和表单验证
             */
            initDisplay: function () {
                //初始化组件渲染
                require(['pageDisplay'], function (Display) {
                    Display.init();
                });
                //初始化表单验证
                require(['formValidation'], function (FormValidation) {
                    FormValidation.init();
                });
                //批量操作不可用
                $('[data-toggle="batchoperate"]').addClass('disabled');
            },

            initEchart: function ($selector) {
                return Echart.init($selector[0]);
            },

            /**
             * 局部刷新
             * @param $refreshTarget 刷新区域一个jquery对象
             * @param params 请求刷新内容的参数
             */
            refresh: function ($refreshTarget, params) {
                var refreshUrl = $refreshTarget.data('refresh-url'),
                    refreshLoading = $refreshTarget.data('refresh-loading'),
                    that = this;

                if (params) {
                    params = $.param(params, true);
                } else {
                    params = {};
                }

                if (refreshLoading || _.isUndefined(refreshLoading)) {
                    refreshLoading = true;
                } else {
                    refreshLoading = false;
                }

                $.ajax({
                    url: refreshUrl,
                    data: params,
                    type: 'get',
                    dataType: 'html',
                    beforeSend: function (req) {
                        req.setRequestHeader("Accept", "text/html");
                    },
                }).done(function (res) {
                    if (res.Errors && !res.Errors.IsValid) {
                        that.errorAlert(res.Errors.ErrorItems[0].ErrorMessage);
                    } else {
                        $refreshTarget.html(res);
                        that.initDisplay();
                    }
                }).fail(function (xhr) {
                    if (xhr.status == 401) {
                        window.location.href = xhr.getResponseHeader('Location');
                    }
                }).always(function () {
                    if (refreshLoading) {
                        $refreshTarget.removeClass('loading');
                    }
                });
                if (refreshLoading) {
                    $refreshTarget.addClass('loading');
                }
            },


            //# 刷新页面中的验证码
            refreshValidateCode: function () {
                this.$('.validate-code').each(function () {
                    var $this = $(this),
                        src = $(this).attr('src'),
                        timestamp = Date.parse(new Date());

                    //判断验证码当前src属性是否包含?
                    if (src.indexOf('?') == -1) {//不包含:src后添加'?+时间戳'
                        $this.attr('src', src + '?' + timestamp)
                    } else {//不包含:src后添加'?+时间戳'
                        var replaceDest = src.substr(src.indexOf('?') + 1);
                        $this.attr('src', src.replace(replaceDest, timestamp))
                    }
                });
            },


            //# 销毁一个Modal
            //# $modal:一个$()对象
            //## bootstrap官方提供的关闭只是隐藏Modal，可能会对后续弹出的Modal产生干扰
            destoryModal: function ($modal) {
                $modal.modal('hide');
                $modal.on('hidden.bs.modal', function (e) {
                    $(this).remove();
                });
            },

            //# 弹出成功提示
            successAlert: function (message) {
                Toastr.options = {
                    "closeButton": false,
                    "debug": false,
                    "newestOnTop": false,
                    "progressBar": false,
                    "positionClass": "toast-top-full-width",
                    "preventDuplicates": false,
                    "onclick": null,
                    "showDuration": "300",
                    "hideDuration": "1000",
                    "timeOut": "5000",
                    "extendedTimeOut": "1000",
                    "showEasing": "swing",
                    "hideEasing": "linear",
                    "showMethod": "fadeIn",
                    "hideMethod": "fadeOut"
                };
                Toastr.success(message);
            },

            //# 弹出错误提示
            errorAlert: function (message) {
                Toastr.options = {
                    "closeButton": false,
                    "debug": false,
                    "newestOnTop": false,
                    "progressBar": false,
                    "positionClass": "toast-top-full-width",
                    "preventDuplicates": false,
                    "onclick": null,
                    "showDuration": "300",
                    "hideDuration": "1000",
                    "timeOut": "5000",
                    "extendedTimeOut": "1000",
                    "showEasing": "swing",
                    "hideEasing": "linear",
                    "showMethod": "fadeIn",
                    "hideMethod": "fadeOut"
                };
                Toastr.error(message);
            },

            //获取时间
            getEndDate: function (startDate, dayCount) {
                var dateArray = startDate.split('-');
                var dd = new Date(dateArray[0], dateArray[1] - 1, dateArray[2]);
                dd.setDate(dd.getDate() + dayCount); //获取dayCount天后的日期
                var y = dd.getFullYear();
                var m = dd.getMonth() + 1; //获取当前月份的日期
                var d = dd.getDate();
                return y + "-" + m + "-" + d;
            },

        });

        return RootView;
    });
